package web.server.io.handler.tst;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.Arrays;
import java.util.List;

public class TSTDecoder extends ByteToMessageDecoder {

    int datagramLength = 32;
    int heartbeatMessageLength = 15;

    byte[] heartbeatBytes = new byte[] {(byte) 0x0B, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x68, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x0C, (byte) 0x68, (byte) 0xF5, (byte) 0x01, (byte) 0x01, (byte) 0xD0, (byte) 0x16};

    byte[] dataFirst = new byte[]{0x1c, 0x00, 0x00, 0x00};

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {

        byte[] data;
        // 标记读索引
        in.markReaderIndex();
        int len = in.readableBytes();
        data = new byte[len];
        in.readBytes(data);
        if (data.length >= heartbeatMessageLength) {

            byte[] data1 = Arrays.copyOfRange(data, 0, heartbeatMessageLength);
            if (Arrays.equals(data1, heartbeatBytes)) {
                in.resetReaderIndex();
                data1 = new byte[data1.length];
                in.readBytes(data1);
                System.out.println("心跳数据 忽略");
            } else {
                data1 = Arrays.copyOfRange(data, 0, datagramLength);
                byte[] data2 = Arrays.copyOfRange(data1, 0, 4);
                byte data3 = data1[data1.length - 1];
                if (Arrays.equals(data2, dataFirst) && data3 == 0x16) {
                    in.resetReaderIndex();
                    data1 = new byte[data1.length];
                    in.readBytes(data1);
                    System.out.println("业务数据");
                    out.add(data1);
                } else {
                    // 回滚读索引
                    in.resetReaderIndex();
                }
            }
        } else  {
            // 回滚读索引
            in.resetReaderIndex();
        }
    }
}
